import { h, resolveComponent } from 'vue'
import { RendererOptions } from 'vxe-table'
import Cell from './cell.vue'
import Editor from './eidtor.vue'
import Formatter from './formatter.vue'
import dayjs from 'dayjs'
import { ElSwitch } from 'element-plus'

type YTableRenderOptions = RendererOptions & { name: string }

const predefineFormatter = {
  date: (value) => value ? [dayjs(value).format('YYYY-MM-DD')] : '',
  dateTime: (value) => value ? [dayjs(value).format('YYYY-MM-DD HH:mm:ss')] : '',
  bool: (value) => h(ElSwitch, { modelValue: value })
}

const renderSpan = (renderOpts, params) => {
  return [params.row[params.column.id]]
}

const renderDefault = (renderOpts, params) => {
  const formatter = renderOpts.props.columnRaw.formatter
  const value = params.row[params.column.id]
  if (typeof formatter === 'function') {
    return h(Formatter, { renderOpts, params })
  }

  if (typeof formatter === 'string') {
    if (predefineFormatter[formatter]) {
      return predefineFormatter[formatter].call(null, value)
    } else {
      return h(resolveComponent(formatter), { modelValue: value })
    }
  }

  if (typeof formatter === 'object') {
    return h(resolveComponent('ComponentRender'), { render: formatter })
  }

  return renderSpan(renderOpts, params)
}

const renderEdit = (renderOpts, params) => {
  if (renderOpts.props.columnRaw.edit) {
    return h(Editor, { renderOpts, params })
  }
  return renderSpan(renderOpts, params)
}

export const YTableCellRender: YTableRenderOptions = {
  name: 'y-table-cell',
  autofocus: 'input.el-input__inner',
  renderCell: renderDefault,
  renderDefault: renderDefault,
  renderEdit: renderEdit
};
